package com.net.xpay.stable.job;

import com.net.common.concurrent.ThreadUtil;
import com.net.xpay.core.manager.safePay.BookAccountChargeOrderManager;
import com.net.xpay.core.service.safePay.SafePayService;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class BookAccountChargeOrderUpdateJob implements Runnable {

    private long shardId;

    private BookAccountChargeOrderManager bookAccountChargeOrderManager;

    private SafePayService safePayService;

    public BookAccountChargeOrderUpdateJob(long shardId, BookAccountChargeOrderManager bookAccountChargeOrderManager, SafePayService safePayService) {
        this.shardId = shardId;
        this.bookAccountChargeOrderManager = bookAccountChargeOrderManager;
        this.safePayService = safePayService;
    }

    @Override
    public void run() {
        try {
            ShardUtil.setShardContext(shardId);
            while (true) {
                try {
                    doUpdateBookAccountChargeOrder();
                } catch (Throwable e) {
                    log.error("doUpdateBookAccountChargeOrder", e);
                }
                ThreadUtil.safeSleep(1000, "");
            }

        } finally {
            ShardUtil.cleanShardContext();
        }
    }

    private void doUpdateBookAccountChargeOrder() {
        List<Long> ids = bookAccountChargeOrderManager.listNeedUpdateOrder();
        for (Long id : ids) {
            try {
                safePayService.updateBookAccountChargeOrder(id);
                ThreadUtil.safeSleep(200, "");
            } catch (Exception e) {
                log.error("doUpdateBookAccountChargeOrder error|id={}", id, e);
            }
        }
    }
}
